<template>
  <div>
    <div style="margin-bottom: 16px">
      <div>
        <a-button type="primary" @click="showAdd"> 新增本地进程 </a-button>
        <a-modal
          title="新增本地进程"
          :visible="visibleAdd"
          @ok="handleOk"
          @cancel="handleCancel"
        >
          <a-form-model-item>
            <a-form-item label="ip地址">
              <a-input
                v-model="addProcessData.ip"
                style="width: 60%; margin-right: 8px"
              />
            </a-form-item>
            <a-form-item label="端口号">
              <a-input
                v-model="addProcessData.port"
                style="width: 60%; margin-right: 8px"
              />
            </a-form-item>
          </a-form-model-item>
        </a-modal>
      </div>
      <a-tooltip placement="top">
        <template slot="title">
          <span>刷新列表</span>
        </template>
        <a-icon
          type="sync"
          style="font-size: 20px; float: right"
          @click="getProcess"
        />
      </a-tooltip>
    </div>
    <a-table
      :columns="columns"
      :data-source="data"
      :row-key="(row) => row.id"
      :pagination="{ pageSize: 50 }"
      :scroll="{ y: this.tableHeight }"
    >
      <template
        v-for="col in ['ip', 'port']"
        :slot="col"
        slot-scope="text, record"
      >
        <div :key="col">
          <a-input
            v-if="record.editable"
            style="margin: -5px 0"
            :value="text"
            @change="(e) => handleChange(e.target.value, record.id, col)"
          />
          <template v-else> {{ text }}</template>
        </div>
      </template>

      <a slot="action" slot-scope="row">
        <a-tooltip placement="top">
          <template slot="title">
            <span>编辑</span>
          </template>
          <span v-if="row.editable">
            <a-icon
              type="check"
              @click="() => save(row.id)"
              style="font-size: 20px"
            />
            <a-popconfirm title="退出更新?" @confirm="() => cancel(row.id)">
              <a-icon type="close" style="font-size: 20px" />
            </a-popconfirm>
          </span>
          <span v-else>
            <a-icon
              type="edit"
              theme="twoTone"
              style="font-size: 20px"
              :disabled="editingKey !== ''"
              @click="() => edit(row.id)"
            />
          </span>
        </a-tooltip>
        <a> {{ "  |  " }}</a>
        <a-tooltip placement="top">
          <template slot="title">
            <span>删除</span>
          </template>
          <a-icon
            type="delete"
            theme="twoTone"
            two-tone-color="red"
            style="font-size: 20px"
            @click="showDeleteConfirm(row.id)"
          />
        </a-tooltip>
      </a>
      <a slot="status" slot-scope="row">
        <a-tooltip placement="top">
          <template slot="title">
            <span>警告！该本地进程不可连通</span>
          </template>
          <a-icon
            :type="!row.status ? 'warning' : 'sync'"
            theme="twoTone"
            two-tone-color="orange"
            style="font-size: 20px"
          />
        </a-tooltip>
        <a-tooltip placement="top">
          <template slot="title">
            <span>该本地进程({{ row.name }})正在运行</span>
          </template>
          <a-icon
            :type="row.name ? 'play-circle' : 'sync'"
            theme="twoTone"
            two-tone-color="green"
            style="font-size: 20px"
          />
        </a-tooltip>
        <a-tooltip placement="top">
          <template slot="title">
            <span>已经准备好运行了</span>
          </template>
          <a-icon
            :type="!row.name && row.status ? 'smile' : 'sync'"
            theme="twoTone"
            two-tone-color="#52c41a"
            style="font-size: 20px"
          />
        </a-tooltip>
      </a>
    </a-table>
  </div>
</template>

<script>
const columns = [
  {
    title: "编号",
    dataIndex: "id",
    sorter: true,
    width: 80,
  },
  {
    title: "ip地址",
    dataIndex: "ip",
    sorter: true,
    width: 150,
    scopedSlots: { customRender: "ip" },
  },
  {
    title: "端口号",
    dataIndex: "port",
    sorter: true,
    width: 120,
    scopedSlots: { customRender: "port" },
  },
  {
    title: "操作",
    width: 150,
    scopedSlots: { customRender: "action" },
  },
  {
    title: "状态",
    scopedSlots: { customRender: "status" },
  },
];

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: "Process",
  data() {
    return {
      columns,
      data: [],
      tableHeight: "300px",
      visibleAdd: false,
      editingKey: "",
      addProcessData: {
        ip: "",
        port: "11114",
      },
    };
  },
  methods: {
    showDeleteConfirm(id) {
      let self = this;
      this.$confirm({
        title: "你确定要删除这条数据？",
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        onOk() {
          self.deleteProcessById(id);
        },
        onCancel() {
          self.infoMessage("已取消删除操作");
        },
        class: "test",
      });
    },
    getTableHeight() {
      let HeaderHeight = 64;
      let FooterHeight = 50;
      let OtherHeight = 120 + 16 + 32 + 5;
      return window.innerHeight - (HeaderHeight + FooterHeight + OtherHeight);
    },
    handleChange(value, key, column) {
      const newData = [...this.data];
      const target = newData.filter((item) => key === item.id)[0];
      if (target) {
        target[column] = value;
        this.data = newData;
      }
    },
    edit(key) {
      const newData = [...this.data];
      const target = newData.filter((item) => key === item.id)[0];
      this.editingKey = key;
      if (target) {
        target.editable = true;
        this.data = newData;
      }
    },
    async save(key) {
      const newData = [...this.data];
      const target = newData.filter((item) => key === item.id)[0];
      if (!this.checkIpAndPort(target.ip, target.port)) {
        return false;
      }
      await this.updateProcessById(key, target);
      this.editingKey = "";
    },
    async updateProcessById(processId, jsonData) {
      let res = await this.ProcessService.updateProcessById(
        processId,
        jsonData
      );
      if (res.code !== "200") {
        return this.errMessage(res.msg);
      }
      await this.getProcess();
      return this.infoMessage(res.msg);
    },
    cancel(key) {
      const newData = [...this.data];
      const target = newData.filter((item) => key === item.id)[0];
      this.editingKey = "";
      if (target) {
        delete target.editable;
        this.data = newData;
      }
      this.getProcess();
    },
    showAdd() {
      this.visibleAdd = true;
    },
    async deleteProcessById(processId) {
      let res = await this.ProcessService.deleteProcessById(processId);
      if (res.code !== "200") {
        return this.errMessage(res.msg);
      }
      await this.getProcess();
      return this.infoMessage(res.msg);
    },
    checkIpAndPort(ip, port) {
      let exp =
        /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
      if (ip === "" || port === "") {
        this.warnMessage("ip地址或者端口号不能为空");
        return false;
      }
      if (ip.match(exp) === null) {
        this.warnMessage("单元ip不合法");
        return false;
      }
      if (parseInt(port) < 0 || parseInt(port) > 65535) {
        this.warnMessage("端口号不合法");
        return false;
      }
      return true;
    },
    // eslint-disable-next-line no-unused-vars
    async handleOk(e) {
      if (
        !this.checkIpAndPort(this.addProcessData.ip, this.addProcessData.port)
      ) {
        return false;
      }

      let res = await this.ProcessService.addProcess(this.addProcessData);
      if (res.code !== "200") {
        this.errMessage(res.msg);
      } else {
        this.successMessage(res.msg);
      }
      await this.getProcess();
    },
    // eslint-disable-next-line no-unused-vars
    handleCancel(e) {
      this.addProcessData = {
        ip: "",
        port: "11114",
      };
      this.visibleAdd = false;
    },
    async getProcess() {
      this.data = await this.ProcessService.getProcess();
      this.infoMessage("更新数据列表");
    },
    infoMessage(Message) {
      this.$message.info(Message);
    },
    warnMessage(Message) {
      this.$message.warn(Message);
    },
    errMessage(Message) {
      this.$message.error(Message);
    },
    successMessage(Message) {
      this.$message.success(Message);
    },
  },
  mounted() {
    this.getProcess();
    this.tableHeight = this.getTableHeight();
    window.onresize = () => {
      return (() => {
        this.tableHeight = this.getTableHeight();
      })();
    };
  },
};
</script>

<style scoped></style>
